import os
import re


from django.core.exceptions import ValidationError as DjangoValidationError
from django.contrib.auth.models import User, Group, Permission
from django.utils.timezone import now
from django.contrib.auth import authenticate

from rest_framework import exceptions, serializers
from rest_framework import mixins
from rest_framework import serializers
from rest_framework.serializers import raise_errors_on_nested_writes,model_meta
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework.exceptions import ErrorDetail, ValidationError
from rest_framework.fields import (  # NOQA # isort:skip
    CreateOnlyDefault, CurrentUserDefault, SkipField, empty
)

from tool import restful

from .models import *

from PIL import Image
# User , Portrait , AddressHistorical , Address , Label , LabelToUser , Invite , UserForget , DataToUser

#登录验证
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        # Add custom claims
        token['name'] = user.username
        return token

# User 用户模型对应序列化器
#用户序列化器
class UserSerializer(serializers.ModelSerializer):
    """
    用户序列化器
    """
    portrait = serializers.ImageField(source='portrait.portrait',read_only=True)
    last_login = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    data_joined = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    sex = serializers.SerializerMethodField()
    # 用户权限
    permission_all = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = "__all__"
    def get_sex(self, obj):
        choices = {"male":"男","female":"女"}
        if obj.sex in choices:
            return choices[str(obj.sex)]
        else:
            return ''
    def get_permission_all(self, obj):
        permission_all = []
        for permission in obj.user_permissions.all():
            permission_all.append(permission.pk)
        for group in obj.groups.all():
            for permission in group.permissions.all():
                permission_all.append(permission.pk)
        return permission_all
#用户下拉列表下拉选
class UserOptionSerializer1(serializers.ModelSerializer):# 无真实名，用于用户间查询
    """
    用户下拉列表下拉选，无真实名，用于用户间查询
    """
    value = serializers.CharField(source='username',read_only=True)
    class Meta:
        model = User
        fields = ['id','value']
class UserOptionSerializer2(serializers.ModelSerializer):# 有真实名，用于管理查询
    """
    用户下拉列表下拉选，有真实名，用于管理查询
    """
    value = serializers.CharField(source='username',read_only=True)
    label = serializers.CharField(source='realname',read_only=True)
    class Meta:
        model = User
        fields = ['id','value', 'label']
# 无信息用户存在与否查询数据返回序列化器
class UserExistsSerializer(serializers.ModelSerializer):
    """
    无信息用户存在与否查询数据返回序列化器
    """
    class Meta:
        model = User
        fields = ['id']


# Portrait 头像模型对应序列化器
#用户头像序列化器
class PortraitSerializer(serializers.ModelSerializer):
    """
    用户头像序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = Portrait
        fields =  "__all__"
    def create(self, validated_data):
        '''序列化器重写创建实例'''
        newportrait = Portrait()
        #传入参数
        picture=validated_data["portrait"]
        newportrait.portrait = picture
        newportrait.save()
        img=Image.open(os.path.dirname(__file__) + '/../../media/' + str(newportrait.portrait))
        # 重写尺寸大小减小内存占用
        new_img = img.resize((180, 180), Image.ANTIALIAS)
        new_img.save(os.path.dirname(__file__) + '/../../media/' + str(newportrait.portrait))
        return newportrait


# AddressHistorical 用户地址修改历史模型对应序列化器
# 地址修改历史序列化器
class AddressHistoricalSerializer(serializers.ModelSerializer):
    """
    用户地址修改历史模型对应序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = AddressHistorical
        fields =  "__all__"


# Address 地址模型对应序列化器
# 地址管理序列化器
class AddressSerializer(serializers.ModelSerializer):
    """
    地址管理序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    desc = serializers.SerializerMethodField()
    class Meta:
        model = Address
        fields = "__all__"
    def get_desc(self, obj):
        return str(obj.country)+str(obj.province)+str(obj.city)+str(obj.town)+str(obj.village)+str(obj.street)
# 地址下拉选序列化器
class AddressOptionSerializer(serializers.ModelSerializer):
    """
    地址下拉选序列化器
    """
    desc = serializers.SerializerMethodField()
    class Meta:
        model = Address
        fields = ['id','desc']
    def get_desc(self, obj):
        return str(obj.country)+str(obj.province)+str(obj.city)+str(obj.town)+str(obj.village)+str(obj.street)


# Label 标签管理模型对应序列化器
# 标签序列化器
class LabelSerializer(serializers.ModelSerializer):
    """
    标签序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = Label
        fields = "__all__"
# 标签下拉选序列化器
class LabelOptionSerializer(serializers.ModelSerializer):
    """
    标签下拉选序列化器
    """
    class Meta:
        model = Label
        fields = ['id','label']


# LabelToUser 标签指向用户模型对应序列化器
# 标签指向用户序列化器
class LabelToUserSerializer(serializers.ModelSerializer):
    """
    标签指向用户序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = LabelToUser
        fields = "__all__"
# 标签指向用户下拉选序列化器
class LabelToUserOptionSerializer(serializers.ModelSerializer):
    """
    标签指向用户下拉选序列化器
    """
    class Meta:
        model = LabelToUser
        fields = ['id','label','user']


# Invite 邀请码管理模型对应序列化器
# 邀请码序列化器
class InviteSerializer(serializers.ModelSerializer):
    """
    邀请码序列化器
    """
    # created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    # last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = Invite
        # fields = "__all__"
        fields = ['id','invite','usetime']


# UserForget 申诉管理模型对应序列化器
#用户忘记密码登记序列化器
class UserForgetSerializer(serializers.ModelSerializer):
    """
    用户忘记密码登记序列化器
    """
    created_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    last_edited_date = serializers.DateTimeField(required=False, format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model = UserForget
        fields =  "__all__"


# DataToUser 用户信息管理模型对应序列化器
# 用户信息管理序列化器
class DataToUserSerializer(serializers.ModelSerializer):
    """
    用户信息管理序列化器
    """
    username = serializers.CharField(source='created_by.username',read_only=True)
    realname = serializers.CharField(source='created_by.realname',read_only=True)
    telephone = serializers.CharField(source='created_by.telephone',read_only=True)
    class Meta:
        model = DataToUser
        fields = ['id','username','realname','telephone','userdata']


# Group Permission 用户分组，权限 内置模型对应序列化器
# 用户分组序列化器，后台用户管理用
class GroupSerializer(serializers.ModelSerializer):
    """
    用户分组序列化器
    """
    user_names = serializers.SerializerMethodField()
    permission_all = serializers.SerializerMethodField()
    permission_admin = serializers.SerializerMethodField()
    permission_auth = serializers.SerializerMethodField()

    permission_user = serializers.SerializerMethodField()
    permission_menu = serializers.SerializerMethodField()
    permission_gold = serializers.SerializerMethodField()
    permission_events = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ['id', 'name', 'user_set', 'user_names', 'permission_all', 'permission_admin', 'permission_auth','permission_bpm','permission_contenttypes','permission_module','permission_pack_rule','permission_sessions','permission_user']
    def get_permission_all(self, obj):
        permission_all = []
        for permission in obj.permissions.all():
            permission_all.append(permission.pk)
        return permission_all
    def get_permission_admin(self, obj):
        permission_admin = []
        for permission in obj.permissions.filter(content_type__app_label__exact='admin'):
            permission_admin.append(permission.pk)
        return permission_admin
    def get_permission_auth(self, obj):
        permission_auth = []
        for permission in obj.permissions.filter(content_type__app_label__exact='auth'):
            permission_auth.append(permission.pk)
        return permission_auth
    
    def get_permission_user(self, obj):
        permission_user = []
        for permission in obj.permissions.filter(content_type__app_label__exact='user'):
            permission_user.append(permission.pk)
        return permission_user
    def get_permission_menu(self, obj):
        permission_menu = []
        for permission in obj.permissions.filter(content_type__app_label__exact='menu'):
            permission_menu.append(permission.pk)
        return permission_menu
    def get_permission_gold(self, obj):
        permission_gold = []
        for permission in obj.permissions.filter(content_type__app_label__exact='gold'):
            permission_gold.append(permission.pk)
        return permission_gold
    def get_permission_events(self, obj):
        permission_events = []
        for permission in obj.permissions.filter(content_type__app_label__exact='events'):
            permission_events.append(permission.pk)
        return permission_events

    def get_user_names(self, obj):
        user_names = ''
        users = obj.user_set.all()
        for user in users:
            user_names += user.realname + ','
        return user_names
# 分组下拉列表下拉选
class GroupOptionSerializer(serializers.ModelSerializer):
    """
    分组序列化器
    """
    value = serializers.CharField(source='id',read_only=True)
    label = serializers.CharField(source='name',read_only=True)
    class Meta:
        model = Group
        fields = ['value', 'label']
# 权限下拉列表下拉选
class PermissionOptionSerializer(serializers.ModelSerializer):
    """
    权限下拉选序列化器
    """
    value = serializers.CharField(source='id',read_only=True)
    label = serializers.SerializerMethodField()
    # label = serializers.CharField(source='name')
    class Meta:
        model = Permission
        fields = ['value', 'label']
    def get_label(self,obj):
        name = obj.name
        if 'Can add ' in name:
            name = name.replace('Can add ','允许添加')
        elif 'Can change ' in name:
            name = name.replace('Can change ','允许修改')
        elif 'Can view ' in name:
            name = name.replace('Can view ','允许查看')
        elif 'Can delete ' in name:
            name = name.replace('Can delete ','允许删除')
        else:
            name = name
        return name

